﻿using BCCServer.Model.Enums;
using BCCServer.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCCServer.DAO.commodity
{
    public class CommodityDB
    {
        private readonly bccContext _context;

        public CommodityDB(bccContext Context)
        {
            _context = Context;
        }

        /// <summary>
        /// 查询商品信息
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<List<SCommodity>> selCommodityAsync(int pageNumber = 1, int pageSize = 20)
        {
            var commodities = await _context.SCommodities.Where(u => !u.IsDelete).OrderByDescending(e => e.CreateTime).AsNoTracking().Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

            return commodities;
        }

        /// <summary>
        /// 库存减一
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int reduceCommodity(int Id)
        {
            try
            {
                var commodities = _context.SCommodities.Where(u => !u.IsDelete && u.Id == Id && u.InventoryQuantity > 0).FirstOrDefault();
                if (commodities != null)
                {
                    commodities.InventoryQuantity--;

                    if (_context.SaveChanges() > 0)
                    {
                        return (int)ResEnums.成功;
                    }
                    else
                    {
                        return (int)ResEnums.失败;
                    }
                }
                else
                {
                    return (int)ResEnums.异常;
                }
            }
            catch (Exception)
            {

                return (int)ResEnums.异常;
            }
        }

        /// <summary>
        /// 添加到购物车
        /// </summary>
        /// <param name="sShoppingcart"></param>
        /// <returns></returns>
        public int addShoppingcart(SShoppingcart sShoppingcart)
        {
            _context.SShoppingcarts.Add(sShoppingcart);
            return _context.SaveChanges();
        }

    }
}
